package com.lagou.web.servlet;

import org.springframework.util.CollectionUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 *
 *
 * @author huangzl
 * @date 2021/7/21
 */
public class MySpringServletContainerInitializer implements ServletContainerInitializer {

	@Override
	public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
		List<WebApplicationInitializer> webApplicationInitializers = new ArrayList<>();
		if (!CollectionUtils.isEmpty(set)) {
			set.forEach(x -> {
				if (!x.isInterface() && !Modifier.isAbstract(x.getModifiers()) && WebApplicationInitializer.class
						.isAssignableFrom(x)) {
					try {
						webApplicationInitializers.add((WebApplicationInitializer) x.newInstance());
					} catch (Throwable e) {
						e.printStackTrace();
					}
				}
			});
		}

		if (!CollectionUtils.isEmpty(webApplicationInitializers)) {
			webApplicationInitializers.forEach(webApplicationInitializer -> {
				try {
					webApplicationInitializer.onStartup(servletContext);
				} catch (ServletException e) {
					e.printStackTrace();
				}
			});
		}
	}
}
